package com.group.activity.listener;


import com.group.activity.dao.BargainListDao;
import com.group.activity.entity.BargainListEntity;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Service
@Slf4j
@RabbitListener(queues = "order.release.order.queue")
public class BargainPastListener {
    @Autowired
    private BargainListDao bargainListDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitHandler
    public void listener(BargainListEntity bargainListEntity, Channel channel, Message message) throws IOException {
        try {
            BargainListEntity bargainListEntity1 = bargainListDao.selectById(bargainListEntity.getBargainingListId());
            System.out.println(bargainListEntity1);
            if (bargainListEntity1.getBargainingStatus()==3){
                log.info("砍价成功");
                return ;
            }
            bargainListEntity1.setBargainingStatus(2);
            //砍价失败
            //获取当前系统时间
            String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date newDate = simpleDateFormat.parse(now);
            bargainListEntity1.setEndTime(newDate);
            bargainListDao.updateById(bargainListEntity1);
            //砍价失败 reids缓存+
            redisTemplate.opsForValue().increment(bargainListEntity1.getBargainId()+"",1);
            log.info("砍价失败");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true);
        }
    }
}
